//
//  UITextView+emo.swift
//  表情栏
//
//  Created by Dengdwd on 15/10/22.
//  Copyright © 2015年 dwd. All rights reserved.
//

import UIKit

extension UITextView {
    
    var imageAttributeText:String  {
        let text = attributedText
        var strM = String()
        text.enumerateAttributesInRange(NSRange(location: 0, length: text.length), options: []) { (dict, range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                strM += attachment.chs ?? ""
            }else{
                strM += (text.string as NSString).substringWithRange(range)
            }
        }
        return strM
    }
    
    
    
    
    func insertEmotition(emotition:Emotition) {
        if emotition.isEmpty {
            return
        }
        if emotition.isRemove {
            deleteBackward()
            return
        }
        if emotition.emoji != nil {
            replaceRange(selectedTextRange!, withText: emotition.emoji!)
            return
        }
        let imageText = EmoticonAttachment.getImageText(emotition, font: font!)
        let strM = NSMutableAttributedString(attributedString: attributedText)
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        let range = selectedRange
        attributedText = strM
        selectedRange = NSRange(location: range.location + 1, length: 0)
        delegate?.textViewDidChange!(self)

    }
}

